package cn.jaye.fabric.common.aspect;


import cn.jaye.fabric.common.util.ResultUtil;
import cn.jaye.fabric.common.constants.exception.ExceptionEnum;
import cn.jaye.fabric.common.model.BaseCommand;
import cn.jaye.fabric.common.util.BeanValidatorsUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author Jaye
 * @create 2017-12-01 10:05
 */
@Aspect
@Order(-1)
@Component
public class ParaValidAspect {

    private static final Logger logger = LoggerFactory.getLogger(ParaValidAspect.class);

    @Around("execution(public * cn.jaye.fabric.controller.*.*(..)) && args(..,command)")
    public Object validatePara(ProceedingJoinPoint point, BaseCommand command) throws Throwable {
        Object[] args = point.getArgs();
        Validator validator = Validation.buildDefaultValidatorFactory()
                .getValidator();
//        Class<?> clz = command.getClass();
//        // 获取实体类的所有属性，返回Field数组
//        Field[] fields = clz.getDeclaredFields();
//        for (Field field : fields){
////            Class<?> cls = Class.forName(); // 取得Class对象
//            Object obj = field.getType().newInstance();
//            if(obj instanceof BaseCommand){
//                List<String> errors1 = BeanValidatorsUtil.extractPropertyAndMessageAsList(validator.validate(obj), " : ");
//                int a=1;
//            }
//        }
        List<String> errors = BeanValidatorsUtil.extractPropertyAndMessageAsList(validator.validate(command), " : ");
        if (errors != null && errors.size() > 0) {
            logger.info("Invalid Parameter:" + errors.toString());
            return ResultUtil.error(ExceptionEnum.INVALID_PARAMETER);
        }
        Object rvt = point.proceed(args);
        return rvt;
    }
}
